package com.example.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.dao.UserRepository;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 *
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;
    @Override
    public User login(User u) {
        if (u.getUsername() == null || u.getPassword() == null) {
            return null;
        }
        User userNode = userRepository.selectByUsernameAndPassword(u.getUsername(), u.getPassword());
        if (userNode == null) {
            return null;
        }
        return userNode;
    }

    @Override
    public JSONObject inert(User u) {
        JSONObject jsonObject = new JSONObject();
        if (u.getUsername() == null || u.getPassword() == null) {
            jsonObject.put("message", "用户名或密码不能为空");
            jsonObject.put("data",  null);
            return jsonObject;
        }
        List<User> userList = userRepository.findAll();
        for (User user:userList) {
            if (u.getUsername().equals(user.getUsername())) {
                jsonObject.put("message", "用户名已存在");
                jsonObject.put("data",  null);
                return jsonObject;
            }
        }
        String uuid = UUID.randomUUID().toString();
        u.setToken(uuid);
        User userNode = userRepository.save(u);
        jsonObject.put("message", "注册成功");
        jsonObject.put("data",  userNode);
        return jsonObject;
    }
}
